package com.gwcm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gwcm.exception.BusinessException;
import com.gwcm.model.dto.memberCard.MemberCardDeleteRequest;
import com.gwcm.model.dto.role.*;
import com.gwcm.model.dto.user.UserQueryRequest;
import com.gwcm.model.dto.user.UserRoleAddRequest;
import com.gwcm.model.entity.MemberCard;
import com.gwcm.model.entity.Role;
import com.gwcm.model.vo.RoleVo;
import com.gwcm.model.vo.UserVo;
import com.gwcm.service.IRoleService;
import com.yhz.commonutil.common.BaseResponse;
import com.yhz.commonutil.common.ErrorCode;
import com.yhz.commonutil.common.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/role")
@Api(tags = "角色接口")
public class RoleController {
    @Resource
    private IRoleService roleService;

    @ApiOperation("分页查询角色接口")
    @PreAuthorize("hasAuthority('system:role:list')")
    @PostMapping("/page")
    public BaseResponse<IPage<RoleVo>> pageModuleTopic(@RequestBody RoleQueryRequest roleQueryRequest) throws BusinessException {
        IPage<RoleVo> roleVoIPage = roleService.pageList(roleQueryRequest);
        return ResultUtils.success(roleVoIPage);
    }

    @ApiOperation("根据ID查询角色")
    @GetMapping("/{roleId}")
    public BaseResponse getById(@PathVariable("roleId") Long roleId){
        return ResultUtils.success(roleService.selectRoleById(roleId));
    }

    @ApiOperation("新增角色")
    @PostMapping("/save")
    public BaseResponse addRole(@RequestBody RoleAddRequest roleAddRequest){
        Role role = new Role();
        BeanUtils.copyProperties(roleAddRequest, role);
        roleService.saveRole(role);
        return ResultUtils.success();
    }

    @ApiOperation("修改角色")
    @PostMapping("/update")
    public BaseResponse updateRole(@RequestBody RoleUpdateRequest roleUpdateRequest){
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateRequest, role);
        roleService.updateRole(role);
        return ResultUtils.success();
    }

    @ApiOperation("删除角色")
    @PostMapping("/delete")
    public BaseResponse deleteRole(@RequestBody RoleDeleteRequest roleDeleteRequest){
        Role role = new Role();
        BeanUtils.copyProperties(roleDeleteRequest, role);
        boolean delete = roleService.removeById(role);
        if(!delete){
            throw new BusinessException(ErrorCode.DELETE_ERROR);
        }
        return ResultUtils.success();
    }
    @ApiOperation("为角色分配菜单")
    @PostMapping("/authRole")
    public BaseResponse insertAuthRole(@RequestBody RoleMenuAddRequest roleMenuAddRequest){
        roleService.insertRoleAuth(roleMenuAddRequest.getRoleId(),roleMenuAddRequest.getMenuIds());
        return ResultUtils.success("分配菜单成功");
    }
}
